#!/bin/sh

busybox httpd -f -vvv -c ./httpd.conf &

# check gae online
while true; do
  gae_online=`wget http://heater.dukelec.com/check_online_web -q -O -`
  if [ $gae_online == 'online' ]; then
    touch /tmp/gae_online
  else
    rm -rf /tmp/gae_online
  fi
  sleep 20
done &

while true; do
  wifi_list=`../hc-list`; echo "$wifi_list" > /tmp/wifi-list.txt
  if [ -e /tmp/gae_online ]; then
    curl -s --data "command=update_scan&value=$wifi_list" http://heater.dukelec.com/net > /dev/null
  fi
  sleep 31
done &

# check gae global dirty
while true; do
  if [ -e /tmp/gae_online ]; then
    gae_dirty=`wget http://heater.dukelec.com/check_dirty -q -O -`
    if [ $gae_dirty == "dirty" ]; then
      # check desired
      get_desired=`curl -s --data "command=get_desired" http://heater.dukelec.com/mcu`
      if [ $get_desired != 'keep' ]; then ../hc-mcu write $get_desired; fi
      # check others ...
    fi
  fi
  sleep 10
done &

after_mcu_set()
{
  goal=`../hc-mcu read goal`; echo $goal > /tmp/mcu-goal.txt
  echo "$goal" > /duke/desired.txt
  curl -s --data "command=update_desired&value=$goal" http://heater.dukelec.com/mcu > /dev/null
}

mcu_set()
{
  if [ -f /tmp/mcu-set.txt ]; then
    ../hc-mcu write `cat /tmp/mcu-set.txt`
    rm /tmp/mcu-set.txt
    after_mcu_set
  fi
}

cp /duke/desired.txt /tmp/mcu-set.txt
sleep 22

while true; do
 
  current=`../hc-mcu read current`; echo $current > /tmp/mcu-temp.txt
  # wget --post-data="command=update_temperature;value=`cat /tmp/mcu-temp.txt`" http://heater.dukelec.com/mcu -q -O -
  if [ -e /tmp/gae_online ]; then
    curl -s --data "command=update_temperature&value=$current" http://heater.dukelec.com/mcu > /dev/null
  fi

  mcu_set

  humidity=`../hc-mcu read humidity`; echo $humidity > /tmp/mcu-humi.txt
  if [ -e /tmp/gae_online ]; then
    curl -s --data "command=update_humidity&value=$humidity" http://heater.dukelec.com/mcu > /dev/null
  fi

  mcu_set

  current=`../hc-mcu read current`; echo $current > /tmp/mcu-temp.txt
  if [ -e /tmp/gae_online ]; then
    curl -s --data "command=update_temperature&value=$current" http://heater.dukelec.com/mcu > /dev/null
  fi

  mcu_set

done &
